<template>
  <div id="logbtn">
    <van-button
      type="primary"
      size="large"
      :color="state.color"
      :round="true"
      :disabled="state.flag"
      @click="getSMS"
    >
      {{ state.title }}
    </van-button>
  </div>
</template>

<script>
import JsEncrypt from "jsencrypt";
import { toRefs, onMounted, reactive } from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { getLoginApi, getKeyApi, getCodeApi } from "../../utils/api";
export default {
  props: {
    state: Object,
    userobj: Object,
  },
  setup(props) {
    const store = useStore();
    const { flag, color, check, title } = toRefs(props.state);
    sessionStorage.setItem("flag", flag);
    sessionStorage.setItem("color", color);
    const router = useRouter();
    let publicKey = "";
    let user = reactive(props.userobj);

    const getSMS = () => {
      if (title.value === "获取短信验证码") {
        if (check.value) {
          smslogin();
        } else {
          Toast({
            message: "请勾选同意协议",
            position: "bottom",
          });
        }
      } else {
        if (check.value) {
          // router.replace("/");
          login();
        } else {
          Toast({
            message: "请勾选同意协议",
            position: "bottom",
          });
        }
      }
    };

    const getkey = async () => {
      const res = await getKeyApi();
      publicKey = res.publicKey;
    };

    const smslogin = async () => {
      let phone = props.userobj.account;
      // console.log(phone);

      const res = await getCodeApi({ phone: phone, templateId: "537707" });
      if (res.status == 0) {
        store.commit("addphone", phone);
        router.push("/verify");
      }
    };

    const login = async () => {
      let en = new JsEncrypt();
      en.setPublicKey(publicKey);
      user.password = en.encrypt(props.userobj.password);
      const res = await getLoginApi(user);
      if (res.status === 0) {
        sessionStorage.setItem("token", res.token);
        Toast.success(res.msg);
        router.replace("/");
      } else {
        Toast.fail(res.msg);
      }
    };
    onMounted(getkey());
    return {
      getSMS,
      user,
      publicKey,
      getkey,
    };
  },
};
</script>
<style lang="less">
#logbtn {
  .van-button {
    width: 100%;
    height: 50px;
  }
}
</style>
